package com.chezhujie.www.controller;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.chezhujie.www.constant.PageInfo;
import com.chezhujie.www.core.image.ImageUtils;
import com.chezhujie.www.core.page.Pagination;
import com.chezhujie.www.domain.Czjfestivalact;
import com.chezhujie.www.domain.Czjfestpic;
import com.chezhujie.www.domain.Czjxyspokesman;
import com.chezhujie.www.enums.OrderType;
import com.chezhujie.www.service.CzjfestivalactService;
import com.chezhujie.www.service.CzjfestpicService;
import com.chezhujie.www.service.CzjrouletteService;
import com.chezhujie.www.service.CzjxyspokesmanService;
import com.chezhujie.www.utils.ConvertObj;
import com.chezhujie.www.utils.UUIDUtils;

@Controller
@RequestMapping("/festivalact")
public class CzjfestivalactController extends BaseController {
	private static final Logger log = LoggerFactory
			.getLogger(CzjfestivalactController.class);

	public CzjfestivalactController() {
	}

	
	/***
	 * 
	 * 方法名：list 显示所有假日
	 * 创建人：RUI
	 * 时间：2017年5月23日-下午3:40:27 
	 * @param czjfestivalact
	 * @param request
	 * @param response
	 * @param pageNo
	 * @param pageSize
	 * @param modelMap
	 * @return String
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value = "list")
	public String list(Czjfestivalact czjfestivalact, HttpServletRequest request,
			HttpServletResponse response, Integer pageNo, Integer pageSize,
			ModelMap modelMap) {

		try {
			if (null == pageNo)
				pageNo = PageInfo.DEFAULT_PAGENO;
			if (null == pageSize)
				pageSize = PageInfo.DEFAULT_PAGESIZE;
			czjfestivalact.setExt3(0);
			Pagination pagination = festivalactService.getFestList(
					ConvertObj.toMap(czjfestivalact), pageSize, pageNo);

			if(null!=czjfestivalact.getExt4()){
				modelMap.addAttribute("ext4",czjfestivalact.getExt4());
			}
			if(null!=czjfestivalact.getFestName()){
				modelMap.addAttribute("festName",czjfestivalact.getFestName());
			}
			if(null!=czjfestivalact.getReserve()){
				modelMap.addAttribute("reserve",czjfestivalact.getReserve());
			}
									
			modelMap.addAttribute("pagination", pagination);
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "fest/fest_list";
	}
	
	
	
	/***
	 * 
	 * 方法名：detail 显示详情
	 * 创建人：RUI
	 * 时间：2017年5月23日-下午3:40:39 
	 * @param festivalActId
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return String
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value = "detail")
	public String detail(@RequestParam(required = true) String festivalActId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {

		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("festivalActId", festivalActId);
			Czjfestivalact czjfestivalact = festivalactService
					.getCzjfestivalact(param);
			modelMap.addAttribute("tm",new Date());
			modelMap.addAttribute("czjfestivalact", czjfestivalact);
			
			
		     Map<String, Object> picmap=new HashMap<String, Object>();
		     	picmap.put("festivalActId", festivalActId);
				List<Czjfestpic> czjfestpics=czjfestpicService.getCzjfestpicList(picmap);
						modelMap.addAttribute("czjfestpics", czjfestpics);
						
						
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0, "102", "查询假日活动详情出错", "", response);
		}

		return "fest/fest_detail";
	}
	
	/**
	 * 跳转都修改或新增页面
	 * 方法名：add
	 * 创建人：RUI
	 * 时间：2017年5月23日-下午3:40:54 
	 * @param festivalActId
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return String
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value = "goAdd")
	public String add(String festivalActId,HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {

		try {
			
			List<Czjxyspokesman> czjxyspokesmans=czjxyspokesmanService.selectAllSpocesman();
			modelMap.addAttribute("czjxyspokesmans", czjxyspokesmans);

			if(null == festivalActId || "".equals(festivalActId)){ //新增页面
				modelMap.addAttribute("czjfestivalact", new Czjfestivalact());
				request.setAttribute("aa", 1);
			}else{ //修改页面
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("festivalActId", festivalActId);
			     Czjfestivalact czjfestivalact = festivalactService.getCzjfestivalact(param);
			     modelMap.addAttribute("czjfestivalact", czjfestivalact);
			     request.setAttribute("aa", 2);
			     //
			     Map<String, Object> picmap=new HashMap<String, Object>();
			     	picmap.put("festivalActId", festivalActId);
					List<Czjfestpic> czjfestpics=czjfestpicService.getCzjfestpicList(picmap);
							modelMap.addAttribute("czjfestpics", czjfestpics);
			     //
			     
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		modelMap.addAttribute("lunpanId", festivalActId);
		return "fest/fest_goAdd";
	}
	
	
	@RequestMapping(value = "getSpokesman")
	public void getSpokesman(@RequestParam(required=true) String spokesmanId ,HttpServletRequest request,HttpServletResponse response){
		
		try {
			Czjxyspokesman czjxyspokesman=czjxyspokesmanService.getSpokesman(spokesmanId);
			
			jsonResult(1, "", "", czjxyspokesman, response);
		} catch (Exception e) {
			jsonResult(0, "146", "服务器错误", "", response);
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * 方法名：doAdd 修改或新增
	 * 创建人：RUI
	 * 时间：2017年5月23日-下午3:41:16 
	 * @param festivalActId
	 * @param pageNo
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return String
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value = "doAdd")
	public String doAdd(Czjfestivalact czjfestivalact,@RequestParam(value="pp",required = false) MultipartFile[] file,
			HttpServletRequest request, HttpServletResponse response,String head,
			ModelMap modelMap) {

		try {
		    String[] festpicId = request.getParameterValues("festpicId");
			String[] sequ = request.getParameterValues("sequ");
			
			Czjfestpic fest=new Czjfestpic();
			if(null!=festpicId){
				
			for(int i=0;i<festpicId.length;i++){
				fest.setFestpicId(festpicId[i]);
				
			
				String reg = "^\\d+$";
				if(Pattern.compile(reg).matcher(sequ[i]).find()){
					fest.setSequ(Integer.valueOf(sequ[i]));//如果转不了,回报错
				}else{
					fest.setSequ(100);
				}
				czjfestpicService.updateCzjfestpic(fest);
			}
			
			}
			/*if(file.getSize()>0){
				String pathRoot = request.getSession().getServletContext()
						.getRealPath("");
				String path = "/upload/" + UUIDUtils.getUUID() + ".jpg";// 数据库保存路径
				 File fileDir = new File(pathRoot + "/upload");
				  if (!fileDir.exists()) {
				      fileDir.mkdir();
				  }
				  file.transferTo(new File(pathRoot + path));
				  czjfestivalact.setFestPic(path);
			}*/
				String pathRoot = request.getSession().getServletContext()
						.getRealPath("");
	
				File fileDir = new File(pathRoot + "/upload");
				if (!fileDir.exists()) {
					fileDir.mkdir();
				}
				for (int i = 0; i < file.length; i++) {
					String path = "/upload/" + UUIDUtils.getUUID();// 数据库保存路径
	
					if(i==0 && file[i].getSize()>0){
						
						if(file[i].getSize()>0){
							file[i].transferTo(new File(pathRoot + path+".jpg"));
								
							/*ImageUtils.fromFile(new File(pathRoot + path+".jpg"))
							.quality(0.6f)
							.fixedGivenSize(true)
							.keepRatio(true)
							.bgcolor(Color.WHITE)	//白色背景
							.toFile(new File(pathRoot+path+"czj.jpg"));
						
							czjfestivalact.setFestPic(path+"czj.jpg");*/
							czjfestivalact.setFestPic(path+".jpg");
						}
					}
					
					if(i==1 && file[i].getSize()>1){
											
						 if(file[i].getSize()>0){
							 
							 file[i].transferTo(new File(pathRoot + path+".jpg"));
								
								/*ImageUtils.fromFile(new File(pathRoot + path+".jpg"))
								.quality(0.6f)
								.fixedGivenSize(true)
								.keepRatio(true)
								.bgcolor(Color.WHITE)	//白色背景
								.toFile(new File(pathRoot+path+"czj.jpg"));
								
								czjfestivalact.setFestPicOne(path+"czj.jpg");*/
							 
							 	czjfestivalact.setFestPicOne(path+".jpg");
							}
					}
					if(i==2 && file[i].getSize()>1){
						
						 
						 if(file[i].getSize()>0){
							 file[i].transferTo(new File(pathRoot + path+".jpg"));
								
								/*ImageUtils.fromFile(new File(pathRoot + path+".jpg"))
								.quality(0.6f)
								.fixedGivenSize(true)
								.keepRatio(true)
								.bgcolor(Color.WHITE)	//白色背景
								.toFile(new File(pathRoot+path+"czj.jpg"));
								
								czjfestivalact.setFestPicTwo(path+"czj.jpg");*/
							 czjfestivalact.setFestPicTwo(path+".jpg");
							}
					}
					if(i==3 && file[i].getSize()>1){
						
						 if(file[i].getSize()>0){
							 file[i].transferTo(new File(pathRoot + path+".jpg"));
								
								/*ImageUtils.fromFile(new File(pathRoot + path+".jpg"))
								.quality(0.6f)
								.fixedGivenSize(true)
								.keepRatio(true)
								.bgcolor(Color.WHITE)	//白色背景
								.toFile(new File(pathRoot+path+"czj.jpg"));
								
								czjfestivalact.setDetailsImg(path+"czj.jpg");*/
							 
							 czjfestivalact.setDetailsImg(path+".jpg");
							}
					}
					if(i==4 && file[i].getSize()>1){
						
						 if(file[i].getSize()>0){
							 file[i].transferTo(new File(pathRoot + path+".jpg"));
								
							/*	ImageUtils.fromFile(new File(pathRoot + path+".jpg"))
								.quality(0.6f)
								.fixedGivenSize(true)
								.keepRatio(true)
								.bgcolor(Color.WHITE)	//白色背景
								.toFile(new File(pathRoot+path+"czj.jpg")); 
								
								czjfestivalact.setActDescPic(path+"czj.jpg");*/
							 
							 czjfestivalact.setActDescPic(path+".jpg");
							}
					}
					if(i==5 && file[i].getSize()>1){
						
						 
						 if(file[i].getSize()>0){
							 file[i].transferTo(new File(pathRoot + path+".jpg"));
								
								/*ImageUtils.fromFile(new File(pathRoot + path+".jpg"))
								.quality(0.6f)
								.fixedGivenSize(true)
								.keepRatio(true)
								.bgcolor(Color.WHITE)	//白色背景
								.toFile(new File(pathRoot+path+"czj.jpg"));
								
								czjfestivalact.setqRcodePic(path+"czj.jpg");*/
							 
							 	czjfestivalact.setqRcodePic(path+".jpg");
							}
					}
				/*	if(i==4 && file[i].getSize()>1){
						
						czjfestivalact.setExt2(path);
					}*/
	
					
	
				}
				if(StringUtils.isNotBlank(head)){
					czjfestivalact.setExt2(head);
				}
				if(StringUtils.isNotBlank(czjfestivalact.getFestVideo())){
					String url=czjfestivalact.getFestVideo();
					if(!url.startsWith("http://") && !url.startsWith("https://")){
						url="http://"+url;
						czjfestivalact.setFestVideo(url);
					}
				}
				if(StringUtils.isNotBlank(czjfestivalact.getFestUrl())){
					String festUrl=czjfestivalact.getFestUrl();
					if(!festUrl.startsWith("http://") && !festUrl.startsWith("https://")){
						festUrl="http://"+festUrl;
						czjfestivalact.setFestUrl(festUrl);
					}
				}
		/*	if(null ==czjfestivalact.getFavorablePrice()){ 
				if(null!=czjfestivalact.getFestAmount()){
				czjfestivalact.setFavorablePrice(czjfestivalact.getFestAmount());	
				}else{
					czjfestivalact.setFavorablePrice(new BigDecimal(0));
					czjfestivalact.setFestAmount(new BigDecimal(0));
				}
				
			}*/
			// 轮盘新增轮盘
			
			//新增赠送二维码
			
			if(null == czjfestivalact.getFestivalActId() || "".equals(czjfestivalact.getFestivalActId())){ //新增
				czjfestivalact.setCreateTime(new Date());
				czjfestivalact.setExt3(0);
				czjfestivalact.setFestivalActId(OrderType.ACTIVITY.getIndex()+UUIDUtils.getUUID().substring(1,19));
				festivalactService.addFestivalAct(czjfestivalact);
				return "redirect:/festivalact/goAdd?festivalActId="+czjfestivalact.getFestivalActId();
			}else{ //修改
				
				if(czjfestivalact.getExt2()==null){
					czjfestivalact.setExt2("");
				}
				festivalactService.updateFestivalAct(czjfestivalact);
				return "redirect:/festivalact/list";
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		

		return null;
	}

	/***
	 * 方法名：doDelete
	 * 创建人：RUI
	 * 时间：2017年5月24日-下午2:08:38 
	 * @param festivalActId
	 * @param pageNo
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return String
	 * @exception 
	 * @since  1.0.0
	 */
	@RequestMapping(value = "doDelete")
	public String doDelete(@RequestParam("ids") List<String> festivalActId,Integer pageNo,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {

		try {
			festivalactService.deleteCzjfestivalactById(festivalActId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/festivalact/list?pageNo="+pageNo;
	}
	
	/** 方法名：uploadImg 上传图片
	 * @throws InterruptedException */
	 
	@RequestMapping("uploadImg")  
	public void uploadImg(String festivalActId,
			@RequestParam(value = "file", required = false) MultipartFile [] multipartFiles,
			HttpServletRequest req, HttpServletResponse resp, ModelMap model) throws InterruptedException {
		
		try {
			
			for(int i=0;i<multipartFiles.length;i++){
				
			
			String pathRoot = req.getSession().getServletContext().getRealPath("");
			String filePath = "/upload/" + UUIDUtils.getUUID();
			File fileDir = new File(pathRoot + "/upload");
			if (!fileDir.exists()) {
				fileDir.mkdir();
			}
			if (multipartFiles != null && multipartFiles[i].getSize() > 0) {
				
				multipartFiles[i].transferTo(new File(pathRoot + filePath+".jpg"));
				/*ImageUtils.fromFile(new File(pathRoot +filePath+".jpg"))
				.quality(0.6f)
				.fixedGivenSize(true)
				.keepRatio(true)
				.bgcolor(Color.WHITE)	//白色背景
				.toFile(new File(pathRoot+filePath+"czj.jpg"));*/
				
				Czjfestpic czjfestpic=new Czjfestpic();
					czjfestpic.setFestivalActId(festivalActId);
					czjfestpic.setCreatetime(new Date());
					czjfestpic.setPicPath(filePath+".jpg");
					Thread.sleep(50);
				czjfestpicService.insertCzjfestpic(czjfestpic);
				
				
			}
			
			}
			
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		jsonResult(1, "", "", "", resp);
	}
	
	/** 删除 **/
	@RequestMapping("deleteImg")
	public void deleteImg(@RequestParam(required = true) String festpicId,@RequestParam(required = true) String festivalActId, HttpServletRequest req,
			HttpServletResponse resp, ModelMap model) {
		try {
			
			Map<String, Object> map=new HashMap<String, Object>();
				map.put("festpicId", festpicId);
			czjfestpicService.deleteCzjfestpic(map);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("failed", e.getMessage());
			jsonResult(0, "","", "", resp);
		}
		jsonResult(1, "","", "", resp);
	}
	
	
	@RequestMapping("QRcode")
	public String QRcode(@RequestParam(required=true) String  festivalActId,String festUrl,HttpServletRequest request, 
			HttpServletResponse response,ModelMap modelMap){
		
		try {
			
			StringBuffer sb=new StringBuffer();
				sb.append("http://" + request.getServerName());//服务器地址  
				sb.append(":");
				sb.append(request.getServerPort());  //端口号  
				sb.append(request.getContextPath());//项目名称  
			if(StringUtils.isBlank(festUrl)){
				sb.append("/html/activity.html?id=");
				sb.append(festivalActId);
				sb.append("&home=1");
				
			}else{
				sb.append("/html/otherHtml.html?id=");
				sb.append(festivalActId);
				sb.append("&flag=1&home=1");
				
				
			}
			modelMap.addAttribute("sb", sb);

					/*+ "/festivalactApi/detail?festivalActId="+festivalActId;*/
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "fest/QRcode";
		
	}
	
	@Resource
	private CzjfestivalactService festivalactService;
	
	@Resource
	private CzjxyspokesmanService czjxyspokesmanService;
	
	@Resource
	private CzjfestpicService czjfestpicService;
	
	@Resource
	private CzjrouletteService czjrouletteService;		

}